﻿using ExcelUnity.Exporter.Exporters;
using System.Collections.Generic;
using System.Data;
using System.Linq;

namespace ExcelUnity.Exporter.Wrappers.SheetWrapperBuilders
{
    public class DynamicTypeBuilder
    {
        public static ExportSheetWrapper? BuildExportSheetWrapper(ExportSheet exportSheet)
        {
            if (exportSheet.Data!.Count == 0) return null;

            var columns = new Dictionary<int, string>();
            var sourceList = new List<IDictionary<string, object>>();

            var colIndex = 0;
            foreach (IDictionary<string, object> row in exportSheet.Data!)
            {
                foreach (var item in row)
                {
                    if (!columns.ContainsValue(item.Key))
                        columns.Add(colIndex++, item.Key);
                }

                sourceList.Add(row);
            }

            var exportRows = new List<ExportRowWrapper>();

            //创建title
            var rowIndex = 0;
            if (exportSheet.Title != null)
            {
                var cells = columns.Select(x => new ExportCellWrapper(x.Key, x.Key == 0 ? exportSheet.Title.Title : string.Empty)
                {
                    MergeColumn = true,
                    CellStyle = x.Key == 0 ? exportSheet.Title.Style : null
                }).ToList();
                var row = new ExportRowWrapper(cells, rowIndex++);
                exportRows.Add(row);
            }

            //创建header
            exportRows.Add(new ExportRowWrapper(columns.Select(x => new ExportCellWrapper(x.Key, false, x.Value)).ToList(), rowIndex++));

            //填充行
            foreach (var row in sourceList)
            {
                var cells = new List<ExportCellWrapper>();
                foreach (var column in columns)
                {
                    if (row.TryGetValue(column.Value, out object cellValueObj) && cellValueObj != null)
                        cells.Add(new ExportCellWrapper(column.Key, false, cellValueObj.ToString()));
                }

                exportRows.Add(new ExportRowWrapper(cells, rowIndex++));
            }

            var columnWrappers = columns.Select(x => new ExportColumnWrapper(x.Key, x.Value)).ToList();
            return new ExportSheetWrapper(columnWrappers, exportRows);
        }
    }
}
